package jbit.dao.impl;

import java.io.Serializable;
import java.sql.Date;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.aspectj.weaver.patterns.ThisOrTargetAnnotationPointcut;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.sun.java_cup.internal.internal_error;

import jbit.constants.Constants;
import jbit.entity.ClaimVoucherDetail;
import jbit.entity.Employee;
import jbit.util.Util;

import jbit.dao.ClaimVoucherDao;
import jbit.entity.ClaimVoucher;

public class ClaimVoucherDaoHibImpl extends HibernateDaoSupport
		implements ClaimVoucherDao {
	
	public ClaimVoucher add(ClaimVoucher claimVoucher){
		getHibernateTemplate().save(claimVoucher);
		return claimVoucher;
	}
	public void deleteById(Serializable id){
		super.getHibernateTemplate().delete(this.get(id));	
	}
	 public ClaimVoucher update(ClaimVoucher claimVoucher){
		 super.getHibernateTemplate().update(claimVoucher);
		 return claimVoucher;
	 }
	 public ClaimVoucher get(Serializable id){
		 ClaimVoucher claimVoucher=(ClaimVoucher)super.getHibernateTemplate().get(ClaimVoucher.class, id);
		 return claimVoucher;
	 }
	 public List<ClaimVoucher> find(ClaimVoucher condition){
		 List<ClaimVoucher> claimVoucherList=super.getHibernateTemplate().findByExample(condition);
		 return claimVoucherList;
	 }
	 /**
	  * 根据报销单id得到报销单信息
	  */
 	    public ClaimVoucher getClaimVoucher(ClaimVoucher claimVoucher) {    	
	        List<ClaimVoucherDetail> list = super.getHibernateTemplate().find(
	        		"from ClaimVoucherDetail c where c.bizClaimVoucher.id=" + claimVoucher.getId());
	        super.getHibernateTemplate().refresh(claimVoucher);
	        claimVoucher.setBizClaimVoucherDetails(list);
	        return claimVoucher;
	    }
	   
 	    /**
	     * 员工查询时得到所有行的方法 当type的值为date时，表示要执行按日期进行查询
	     */
	    public int getAllRowCount(final String hql,final ClaimVoucher condition, final Employee employee,
	            final String type) {
	        @SuppressWarnings("unchecked")
	        List<String> totalNum = getHibernateTemplate().executeFind(new HibernateCallback(){
	                	//HibernateCallback是一个接口，
	                	//该接口只有一个方法doInHibernate(org.hibernate.Session session)，
	                	//该方法只有一个参数Session

	                    public Object doInHibernate(Session session)throws HibernateException, SQLException {
	                        Query query = session.createQuery(hql);
	                        if (!"".equals(employee.getSn())) {
	                            query.setString("creatorSn", employee.getSn());
	                        }
	                        setQueryDate(type, condition, query);
	                        //当确定返回的实例只有一个或者null时 用uniqueResult()方法 否则用list List list = query.list();  
	                        String num = query.uniqueResult().toString();
	                        List<String> list = new ArrayList<String>();
	                        list.add(num);
	                        return list;
	                    }
	                });

	        return Integer.parseInt(totalNum.get(0));
	    }
	    
	    
	    private void setQueryDate(final String type,final ClaimVoucher condition, Query query){
	        if (null != type && !"".equals(condition.getCreateTime())) {
	            String date = condition.getCreateTime().toString().substring(0, 7);
	            String date1 = date + "-01";
	            String date2 = date + "-31";
	            Date newDate1 = Util.parseSqlDate(date1);
	            Date newDate2 = Util.parseSqlDate(date2);
	            query.setDate("date1", newDate1);
	            query.setDate("date2", newDate2);
	        }
	    }
	    
	    
	    /*
	     * 员工提交或保存报销单后执行的查询方法
	     * 当type的值为date时，表示要执行安日期进行查询
	     */
	    public List<ClaimVoucher> queryForPage(final String hql,
	            final int offset, final int length,
	            final ClaimVoucher condition, final Employee employee,
	            final String type) {
	        @SuppressWarnings("unchecked")
	        List<ClaimVoucher> list = getHibernateTemplate().executeFind(
	                new HibernateCallback() {
	                    public Object doInHibernate(Session session)
	                            throws HibernateException, SQLException {
	                        Query query = session.createQuery(hql);

	                        if (!"".equals(employee.getSn())) {
	                            query.setString("creatorSn", employee.getSn());
	                        }
	                        setQueryDate(type, condition, query);

	                        return getListForPage(query, offset, length);
	                    }
	                });
	        return list;
	    }
	    @SuppressWarnings({ "unused", "unchecked" })
	    private List getListForPage(Query query, int offset, int length){
	        query.setFirstResult(offset);
	        query.setMaxResults(length);
	        return query.list();
	    }
	    /*
	     * 部门经理查询报销单方法 当type的值为date时，表示要执行安日期进行查询
	     */
	    public List<ClaimVoucher> queryForPageM(final String hql,
	            final int offset, final int length,
	            final ClaimVoucher condition, final Employee employee,
	            final String type) {
	        @SuppressWarnings("unchecked")
	        List<ClaimVoucher> list = getHibernateTemplate().executeFind(
	                new HibernateCallback() {
	                    public Object doInHibernate(Session session)
	                            throws HibernateException, SQLException {
	                        Query query = session.createQuery(hql);
	                        if (employee.getSysPosition().getNameCn().equals(
	                                Constants.POSITION_FM)) {
	                            if (employee != null && !"".equals(employee.getSn())) {
	                                query.setLong("departmentId", employee.getSysDepartment().getId());
	                            }
	                            if (!"".equals(condition.getStatus())) {
	                                query.setString("status", condition.getStatus());
	                            }
	                            setQueryDate(type, condition, query);
	                        } else if (employee.getSysPosition().getNameCn().equals(Constants.POSITION_GM)
	                                || employee.getSysPosition().getNameCn().equals(Constants.POSITION_CASHIER)) {
	                            if (null != employee.getSn() && !"".equals(employee.getSn())) {
	                                query.setString("nextDealSn", employee.getSn());
	                            }
	                            setQueryDate(type, condition, query);
	                        }

	                        return getListForPage(query, offset, length);
	                    }
	                });
	        return list;
	    }
	    
	    /*
	     * 部门经理执行查询时调用该方法查询出总条数 当type的值为date时，表示要执行安日期进行查询
	     */
	    public int getAllRowCountM(final String hql,
	            final ClaimVoucher condition, final Employee employee,
	            final String type) {
	        @SuppressWarnings("unchecked")
	        List<String> totalNum = getHibernateTemplate().executeFind(
	                new HibernateCallback() {
	                    public Object doInHibernate(Session session)
	                            throws HibernateException, SQLException {
	                        Query query = session.createQuery(hql);
	                        if (employee.getSysPosition().getNameCn().equals(Constants.POSITION_FM)) {
	                            if (null != employee.getSn() && !"".equals(employee.getSn())) {
	                                query.setLong("departmentId", employee.getSysDepartment().getId());
	                            }
	                            if (!"".equals(condition.getStatus())) {
	                                query.setString("status", condition.getStatus());
	                            }
	                            setQueryDate(type, condition, query);
	                        } else if (employee.getSysPosition().getNameCn().equals(Constants.POSITION_GM)
	                                || employee.getSysPosition().getNameCn().equals(Constants.POSITION_CASHIER)) {
	                            if (null != employee.getSn() && !"".equals(employee.getSn())) {
	                                query.setString("nextDealSn", employee.getSn());
	                            }
	                            setQueryDate(type, condition, query);
	                        }

	                        String num = query.uniqueResult().toString();
	                        List<String> list = new ArrayList<String>();
	                        list.add(num);
	                        return list;
	                    }
	                });

	        return Integer.parseInt(totalNum.get(0));
	    }
	    
	    
	    public void deletClaimVoucher(ClaimVoucher claimVoucher){
	    	 
	    	claimVoucher=(ClaimVoucher)super.getHibernateTemplate().get
	    	(ClaimVoucher.class, claimVoucher.getId());
	    	 List<ClaimVoucherDetail> list = super.getHibernateTemplate().find(
		        		"from ClaimVoucherDetail c where c.bizClaimVoucher.id=" + claimVoucher.getId());
            for(int i=0;i<list.size();i++){
    	    	super.getHibernateTemplate().delete(list.get(i));
            }

	    	super.getHibernateTemplate().delete(claimVoucher);
	    }
	    


}

